<template>
  <div class="notice-container">
    <div class="page-header">
      <h2 class="page-title">公告管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateNotice">
          <el-icon><Plus /></el-icon>新增公告
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="标题">
          <el-input v-model="filterForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="filterForm.type" placeholder="请选择公告类型" clearable>
            <el-option label="滚动公告" :value="0" />
            <el-option label="弹窗公告" :value="1" />
            <el-option label="通知" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 公告表格 -->
    <div class="notice-table">
      <el-table
        :data="noticeList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="title" label="公告标题" min-width="180" />
        <el-table-column prop="type" label="公告类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="公告内容" min-width="250">
          <template #default="scope">
            <div class="notice-content-preview">{{ scope.row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEditNotice(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDeleteNotice(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑公告对话框 -->
    <el-dialog
      v-model="noticeDialog.visible"
      :title="noticeDialog.isEdit ? '编辑公告' : '新增公告'"
      width="700px"
    >
      <el-form
        ref="noticeFormRef"
        :model="noticeForm"
        :rules="noticeRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="noticeForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-radio-group v-model="noticeForm.type">
            <el-radio :label="0">滚动公告</el-radio>
            <el-radio :label="1">弹窗公告</el-radio>
            <el-radio :label="2">通知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效时间" prop="effectiveTime">
          <el-date-picker
            v-model="noticeForm.effectiveTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="noticeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="noticeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitNoticeForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

export default {
  name: 'NoticeList',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 模拟公告数据
    const mockNotices = [
      {
        id: 1,
        title: '系统例行维护通知',
        type: 1, // 弹窗公告
        content: '尊敬的用户，系统将于2023年05月15日凌晨2:00-4:00进行例行维护，届时系统将暂停服务。感谢您的理解与支持！',
        startTime: '2023-05-14 00:00:00',
        endTime: '2023-05-15 23:59:59',
        status: 1, // 启用
        createTime: '2023-05-10 10:30:00'
      },
      {
        id: 2,
        title: '业务办理须知',
        type: 0, // 滚动公告
        content: '请各位用户在办理业务前准备好相关证件，包括身份证、户口本等，以便快速办理相关业务。',
        startTime: '2023-05-01 00:00:00',
        endTime: '2023-12-31 23:59:59',
        status: 1, // 启用
        createTime: '2023-04-28 14:20:00'
      },
      {
        id: 3,
        title: '办公时间调整',
        type: 2, // 通知
        content: '由于国家法定节假日安排，6月22日至6月24日期间办公时间调整为上午9:00-12:00，请提前安排好办事时间。',
        startTime: '2023-06-01 00:00:00',
        endTime: '2023-06-24 23:59:59',
        status: 1, // 启用
        createTime: '2023-05-25 09:15:00'
      },
      {
        id: 4,
        title: '新业务上线通知',
        type: 1, // 弹窗公告
        content: '我们很高兴地通知您，从2023年7月1日起，我们将推出全新的"一站式企业服务"业务，欢迎企业用户前来办理。',
        startTime: '2023-06-20 00:00:00',
        endTime: '2023-07-20 23:59:59',
        status: 1, // 启用
        createTime: '2023-06-15 11:45:00'
      },
      {
        id: 5,
        title: '旧版系统停用通知',
        type: 2, // 通知
        content: '旧版业务系统将于2023年8月1日起停止使用，请各位用户及时迁移到新系统。如有疑问，请咨询工作人员。',
        startTime: '2023-07-01 00:00:00',
        endTime: '2023-08-01 23:59:59',
        status: 0, // 禁用
        createTime: '2023-06-28 16:30:00'
      },
      {
        id: 6,
        title: '关于完善个人信息的通知',
        type: 0, // 滚动公告
        content: '为提供更好的服务体验，请各位用户及时更新个人信息，包括手机号码、邮箱等联系方式。',
        startTime: '2023-04-01 00:00:00',
        endTime: '2023-12-31 23:59:59',
        status: 1, // 启用
        createTime: '2023-03-25 10:00:00'
      },
      {
        id: 7,
        title: '疫情防控提示',
        type: 1, // 弹窗公告
        content: '为了您和他人的健康安全，请进入办公区域时佩戴口罩，配合工作人员进行体温检测，谢谢配合。',
        startTime: '2023-01-01 00:00:00',
        endTime: '2023-12-31 23:59:59',
        status: 1, // 启用
        createTime: '2022-12-28 09:00:00'
      },
      {
        id: 8,
        title: 'APP下载提示',
        type: 0, // 滚动公告
        content: '为提供更便捷的服务，我们推出了移动APP，扫描大厅二维码即可下载使用，支持预约、查询等功能。',
        startTime: '2023-03-15 00:00:00',
        endTime: '2023-12-31 23:59:59',
        status: 1, // 启用
        createTime: '2023-03-10 14:00:00'
      }
    ]
    
    // 存储所有公告数据
    const allNotices = ref([...mockNotices])
    // 显示的公告列表
    const noticeList = ref([])
    const tableLoading = ref(false)
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: mockNotices.length
    })
    
    // 过滤表单
    const filterForm = reactive({
      title: '',
      type: '',
      status: ''
    })
    
    // 公告对话框
    const noticeDialog = reactive({
      visible: false,
      isEdit: false
    })
    
    // 公告表单
    const noticeFormRef = ref(null)
    const noticeForm = reactive({
      id: null,
      title: '',
      type: 0,
      content: '',
      effectiveTime: [],
      startTime: '',
      endTime: '',
      status: 1
    })
    
    // 表单验证规则
    const noticeRules = {
      title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
        { max: 100, message: '标题最多100个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择公告类型', trigger: 'change' }
      ],
      effectiveTime: [
        { required: true, message: '请选择有效时间', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 基于过滤条件获取公告列表
    const fetchNoticeList = () => {
      tableLoading.value = true
      
      // 模拟网络请求延迟
      setTimeout(() => {
        // 过滤数据
        const filteredData = allNotices.value.filter(item => {
          const titleMatch = !filterForm.title || item.title.includes(filterForm.title)
          const typeMatch = filterForm.type === '' || item.type === filterForm.type
          const statusMatch = filterForm.status === '' || item.status === filterForm.status
          
          return titleMatch && typeMatch && statusMatch
        })
        
        // 更新总数
        pagination.total = filteredData.length
        
        // 应用分页
        const start = (pagination.currentPage - 1) * pagination.pageSize
        const end = start + pagination.pageSize
        
        // 更新列表数据
        noticeList.value = filteredData.slice(start, end)
        
        tableLoading.value = false
      }, 300)
    }
    
    // 监听过滤条件变化
    watch([() => filterForm.title, () => filterForm.type, () => filterForm.status], () => {
      pagination.currentPage = 1
      fetchNoticeList()
    })
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchNoticeList()
    }
    
    // 重置过滤器
    const resetFilter = () => {
      filterForm.title = ''
      filterForm.type = ''
      filterForm.status = ''
      pagination.currentPage = 1
      fetchNoticeList()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      fetchNoticeList()
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      fetchNoticeList()
    }
    
    // 处理刷新
    const handleRefresh = () => {
      fetchNoticeList()
    }
    
    // 获取类型标签样式
    const getTypeTag = (type) => {
      switch(type) {
        case 0: return 'info'    // 滚动公告
        case 1: return 'warning' // 弹窗公告
        case 2: return ''        // 通知
        default: return 'info'
      }
    }
    
    // 获取类型文本
    const getTypeText = (type) => {
      switch(type) {
        case 0: return '滚动公告'
        case 1: return '弹窗公告'
        case 2: return '通知'
        default: return '未知类型'
      }
    }
    
    // 处理创建公告
    const handleCreateNotice = () => {
      noticeDialog.isEdit = false
      noticeDialog.visible = true
      
      // 重置表单
      noticeFormRef.value?.resetFields()
      noticeForm.id = null
      noticeForm.title = ''
      noticeForm.type = 0
      noticeForm.content = ''
      noticeForm.effectiveTime = []
      noticeForm.startTime = ''
      noticeForm.endTime = ''
      noticeForm.status = 1
    }
    
    // 处理编辑公告
    const handleEditNotice = (row) => {
      noticeDialog.isEdit = true
      noticeDialog.visible = true
      
      // 填充表单数据
      noticeForm.id = row.id
      noticeForm.title = row.title
      noticeForm.type = row.type
      noticeForm.content = row.content
      noticeForm.effectiveTime = [row.startTime, row.endTime]
      noticeForm.startTime = row.startTime
      noticeForm.endTime = row.endTime
      noticeForm.status = row.status
    }
    
    // 处理删除公告
    const handleDeleteNotice = (row) => {
      ElMessageBox.confirm(`确定要删除公告"${row.title}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中删除
        const index = allNotices.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          allNotices.value.splice(index, 1)
          ElMessage.success('删除公告成功')
          fetchNoticeList()
        }
      }).catch(() => {})
    }
    
    // 处理切换状态
    const handleToggleStatus = (row) => {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      ElMessageBox.confirm(`确定要${statusText}公告"${row.title}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 更新模拟数据中的状态
        const index = allNotices.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          allNotices.value[index].status = newStatus
          ElMessage.success(`${statusText}公告成功`)
          fetchNoticeList()
        }
      }).catch(() => {})
    }
    
    // 提交公告表单
    const submitNoticeForm = () => {
      noticeFormRef.value.validate((valid) => {
        if (valid) {
          if (!noticeForm.effectiveTime || noticeForm.effectiveTime.length !== 2) {
            ElMessage.error('请选择有效的时间范围')
            return
          }
          
          // 提取时间范围
          const [startTime, endTime] = noticeForm.effectiveTime
          
          if (noticeDialog.isEdit) {
            // 编辑现有公告
            const index = allNotices.value.findIndex(item => item.id === noticeForm.id)
            if (index !== -1) {
              allNotices.value[index] = {
                ...allNotices.value[index],
                title: noticeForm.title,
                type: noticeForm.type,
                content: noticeForm.content,
                startTime,
                endTime,
                status: noticeForm.status
              }
              ElMessage.success('更新公告成功')
            }
          } else {
            // 创建新公告
            const now = new Date()
            const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
            
            // 生成新ID（模拟数据中的最大ID加1）
            const newId = Math.max(...allNotices.value.map(item => item.id), 0) + 1
            
            allNotices.value.push({
              id: newId,
              title: noticeForm.title,
              type: noticeForm.type,
              content: noticeForm.content,
              startTime,
              endTime,
              status: noticeForm.status,
              createTime
            })
            ElMessage.success('创建公告成功')
          }
          
          noticeDialog.visible = false
          fetchNoticeList()
        }
      })
    }
    
    // 初始化
    onMounted(() => {
      fetchNoticeList()
    })
    
    return {
      noticeList,
      tableLoading,
      pagination,
      filterForm,
      noticeDialog,
      noticeFormRef,
      noticeForm,
      noticeRules,
      getTypeTag,
      getTypeText,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateNotice,
      handleEditNotice,
      handleDeleteNotice,
      handleToggleStatus,
      submitNoticeForm
    }
  }
}
</script>

<style scoped>
.notice-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.notice-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.notice-content-preview {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 